//
//  ComposeViewController.swift
//  weibo
//
//  Created by yellow on 15/10/26.
//  Copyright © 2015年 yellow. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 微博文本最大长度
let WeiboTextMaxLength = 10

/// 发布微博控制器
class ComposeViewController: UIViewController {
    
/// 关闭modal控制器
    @objc private func dismissVC(){
        //先退出键盘，在关闭vc。不然会出现，窗口关闭了，而键盘却过一段时间才退出
        self.ContentView.resignFirstResponder()
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
/// 发布微博
    @objc private func composeWeibo(){
        let weiboText = self.ContentView.emojiText
        SVProgressHUD.show()
        //从图片选择器中的photos获取单张图片(weibo只允许第三方应用传递一张图片)
        let img = photoPickerViewController.photos.last
        WeiboAPIManager.manager.composeWeibo(weiboText, weiboPicture: img) { (result, error) -> (Void) in
            if error != nil{
                SVProgressHUD.showInfoWithStatus("您的网络不给力", maskType: .Gradient)
                return
            }else{
                SVProgressHUD.dismiss()
                self.dismissVC()
            }
        }
    }

    
    override func loadView() {
        view = UIView()
        view.backgroundColor = UIColor.whiteColor()
        setUI()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        //提高用户友好度，当进入发布界面就弹出键盘，让用户有想写点什么的冲动
        
        // 激活键盘 - 如果已经存在照片控制器视图，不再激活键盘
        if photoPickerViewController.view.frame.height == 0 {
            ContentView.becomeFirstResponder()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //添加键盘弹出高度的通知，为了能让底部的工具栏也能跟着键盘一起叫上来
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
/// 添加通知，一定要在析构函数中注销通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
/// 键盘高度将要改变的通知
    @objc private func keyboardChange(notification:NSNotification){
        let duration = (notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let rect = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //获取动画曲线选项,可以让键盘收回或者弹起动画，从当前位置做动画，而不是等上一个动画完成后再执行
        //第二：当键盘进行切换的时候，工具栏不会跳的幅度大
        let curve = (notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        
        //计算工具栏需要向上的偏移量
        let offset = -view.bounds.height + rect.origin.y
        
        toolsBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(self.view.snp_bottom).offset(offset)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            //强制刷新布局
            self.view.layoutIfNeeded()
        }
    }
    
/// 工具栏选择emoji键盘
    @objc private func selectedEmojiView(){
        //要想叫出emoji键盘，需要将原来的键盘注销掉
        ContentView.resignFirstResponder()
        //点击emoji工具啦进行普通键盘和emoji键盘切换
        ContentView.inputView = ContentView.inputView == nil ? emojiView : nil
        ContentView.becomeFirstResponder()
    }
    
    /// 工具栏选择图片选择器
    @objc private func selectedPhotoPickerView(){
        //要想叫出emoji键盘，需要将原来的键盘注销掉
        ContentView.resignFirstResponder()
        
        photoPickerViewController.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(view.bounds.height*0.6)
        }
        
        ContentView.snp_remakeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(self.view.snp_left)
            make.right.equalTo(self.view.snp_right)
            make.bottom.equalTo(photoPickerViewController.view.snp_top)
        }
        
        UIView.animateWithDuration(0.5) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    ///懒加载控件
    private lazy var titleLable:UILabel = UILabel(title: "发微博", color: UIColor.darkGrayColor(), fontSize: 14)
    ///微博名
    private lazy var Screen_nameLable:UILabel = UILabel(title: UserAccountViewModel.sharedViewModel.userScreen_name ?? "", color: UIColor.lightGrayColor(), fontSize: 14)
    
    /// 添加微博文本控件
    private lazy var ContentView:UITextView = {
        let textView = UITextView()
        textView.font = UIFont.systemFontOfSize(18)
        // 允许垂直滚动
        textView.alwaysBounceVertical = true
        //设置textView拖动时关闭键盘
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        textView.delegate = self
        return textView
    }()
    
    //分享新鲜事占位标签
    private lazy var placeholderLable:UILabel = UILabel(title: "分享新鲜事。。。", color: UIColor.lightGrayColor(), fontSize: 18)
    
    private lazy var emojiView:EmojiView = EmojiView { (emoji) -> () in
        self.ContentView.insertEmoji(emoji)
        //强制执行UITextView的textViewDidChange方法
    }
    
    /// 图片选择器控制器
    private lazy var photoPickerViewController:PhotoPickerViewController = PhotoPickerViewController()
    
    //微博文本长度提示标签
    private lazy var lengthLable:UILabel = UILabel(title: "\(WeiboTextMaxLength)", color: UIColor.darkGrayColor(), fontSize: 14)
    
    /// 底部工具栏
    private lazy var toolsBar:UIToolbar = UIToolbar()

}

// MARK: - UITextViewDelegate
extension ComposeViewController:UITextViewDelegate{
    
    //当文本发生改变时，需要将占位标签隐藏掉,只要有文本就使得发布按钮可用
    func textViewDidChange(textView: UITextView) {
        placeholderLable.hidden = self.ContentView.hasText()
        navigationItem.rightBarButtonItem?.enabled = self.ContentView.hasText()
        
        //过长的提示
        let text = textView.emojiText
        if text.characters.count > WeiboTextMaxLength {
            SVProgressHUD.showInfoWithStatus("文本过长", maskType: SVProgressHUDMaskType.Gradient)
            textView.deleteBackward()
            return
        }else{
            //实时显示剩余可写入的字数
            let leftTextCount = WeiboTextMaxLength - text.characters.count
            lengthLable.text = String(leftTextCount)
            lengthLable.textColor = (leftTextCount > 0 ? UIColor.darkGrayColor():UIColor.redColor())
        }
    }

}

extension ComposeViewController{

    //界面初始化设置
    private func setUI(){
        
        // 0. 取消自动调整滚动视图间距(会添加一个内边距)， status bar, navigation bar, and toolbar or tab bar.都有类似的效果，让其view有穿过他们的感觉、
        automaticallyAdjustsScrollViewInsets = false
        prepareNavBar()
        prepareToolsBar()
        preparePhotoPickerViewController()
        prepareContentView()
    }
    
    /// 设置导航栏界面
    private func prepareNavBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "dismissVC")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "composeWeibo")
        //默认设置发布按钮不可用
        navigationItem.rightBarButtonItem?.enabled = false
        
        //设置中间view为  上：发微博 下：微博名
        let topView = UIView(frame: CGRectMake(0, 0, 200, 36))
        navigationItem.titleView = topView
        
        topView.addSubview(titleLable)
        topView.addSubview(Screen_nameLable)
        
        //自动布局
        titleLable.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(topView.snp_top)
            make.centerX.equalTo(topView.snp_centerX)
        }
        
        Screen_nameLable.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleLable.snp_bottom)
            make.centerX.equalTo(titleLable.snp_centerX)
        }
    }
    
    private func preparePhotoPickerViewController(){
        addChildViewController(photoPickerViewController)
        view.insertSubview(photoPickerViewController.view, belowSubview: toolsBar)
        //自动布局，放置在屏幕高度的60%处
        
        photoPickerViewController.view.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(0)
        }
    }
    
/// 设填写微博文本的控件
    private func prepareContentView(){
        view.addSubview(ContentView)
        
        //添加占位文本
        ContentView.addSubview(placeholderLable)
        //将文字个数提示标签加入文本框中
        view.addSubview(lengthLable)
        
        //因为ContentView的约束依赖于toolsBar，所以要先把toolsBar添加到视图中，不然会报安装约束失败
        ContentView.snp_makeConstraints { (make) -> Void in
            //snp_topLayoutGuideBottom屏幕上方任何遮挡内容的栏的最底部,辅助自动布局用的
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(self.view.snp_left)
            make.right.equalTo(self.view.snp_right)
            make.bottom.equalTo(toolsBar.snp_top)
        }
        
        placeholderLable.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(ContentView.snp_top).offset(8)
            make.left.equalTo(ContentView.snp_left).offset(4)
        }
        
        //个数提示标签放置在工具栏的上右上方
        lengthLable.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(ContentView.snp_right).offset(-8)
            make.bottom.equalTo(ContentView.snp_bottom).offset(-8)
        }
    }
    
/// 底部工具栏
    private func prepareToolsBar(){
        view.addSubview(toolsBar)
        
        toolsBar.backgroundColor = UIColor.darkGrayColor()
        
        toolsBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self.view.snp_bottom)
            make.left.equalTo(self.view.snp_left)
            make.right.equalTo(self.view.snp_right)
            //一般底部工具栏高度为44
            make.height.equalTo(44)
        }
        
        // 添加工具栏按钮
        let itemSettings = [["imageName": "compose_toolbar_picture","action":"selectedPhotoPickerView"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","action":"selectedEmojiView"],
            ["imageName": "compose_addbutton_background"]]
        
        //使用UIBarButtonItem是因为UIToolbar需要UIBarButtonItem，但是我们已有button的便利构造函数，所以使用btn外面包装UIBarButtonItem,而且可以通过barButton中的弹簧就可以设置间距了，而不用在写自动布局代码了
        var itemBtns = [UIBarButtonItem()]
        for item in itemSettings{
            let barButton = UIBarButtonItem(imageName: item["imageName"]!, target: self, actionName: item["action"])
            itemBtns.append(barButton)
            itemBtns.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        itemBtns.removeLast()
        toolsBar.items = itemBtns
    }
    
    
    
}













